package com.internetCafes.spms.web.extend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.internetCafes.spms.web.extend.entity.EntSysMonitorLog;
import com.internetCafes.spms.web.extend.mapper.EntSysMonitorLogMapper;
import com.internetCafes.spms.web.extend.service.IEntSysMonitorLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.internetCafes.spms.web.job.utils.SystemTestMessageUtil;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Zj
 * @since 2021-07-04
 */
@Service
public class EntSysMonitorLogServiceImpl extends ServiceImpl<EntSysMonitorLogMapper, EntSysMonitorLog> implements IEntSysMonitorLogService {

    /**
     * 对系统错误进行报错并发送短信
     *
     * @param sysName    系统名称
     * @param apiName    接口名称
     * @param apiUrl     接口url
     * @param errorInfo  错误信息
     * @param createTime 创建时间
     */
    @Override
    public void addAndSendMessage(String sysName, String apiName, String apiUrl, String errorInfo, Date createTime, String noticeMobile) {
        EntSysMonitorLog entSysMonitorLogDo = new EntSysMonitorLog();
        entSysMonitorLogDo.setSysName(sysName)
                .setApiName(apiName)
                .setApiUrl(apiUrl)
                .setNoticeMobile(noticeMobile)
                .setHandleFlag(0)
                .setNoticeFlag(0);
        // 查看是否是首次通知
        QueryWrapper<EntSysMonitorLog> queryWrapper = new QueryWrapper<>(entSysMonitorLogDo);
        List<EntSysMonitorLog> logs = list(queryWrapper);
        if (CollectionUtils.isEmpty(logs)) {
            // 存入第一条日志
            entSysMonitorLogDo.setCreateTime(createTime)
                    .setErrorInfo(errorInfo);
            save(entSysMonitorLogDo);
        } else {
            // 第二次以后发送短信 后修改状态
            SystemTestMessageUtil.sendMessage(sysName, apiName, errorInfo, noticeMobile);
            List<Long> ids = logs.stream().map(EntSysMonitorLog::getId)
                    .collect(Collectors.toList());
            UpdateWrapper<EntSysMonitorLog> entSysMonitorLogUpdateWrapper = new UpdateWrapper<>();
            entSysMonitorLogUpdateWrapper.in("id", ids)
                    .set("notice_flag", 1);
            update(entSysMonitorLogUpdateWrapper);
        }
    }
}
